package com.meirengu.webview.service.impl;

import com.meirengu.common.RedisClient;
import com.meirengu.service.impl.BaseServiceImpl;
import com.meirengu.utils.DateUtils;
import com.meirengu.webview.common.Constants;
import com.meirengu.webview.common.UserChannelEnum;
import com.meirengu.webview.dao.KwInterfaceConfigDao;
import com.meirengu.webview.model.KwDfrzFilter;
import com.meirengu.webview.model.KwInterfaceConfig;
import com.meirengu.webview.model.User;
import com.meirengu.webview.model.UserInfo;
import com.meirengu.webview.service.KwDfrzFilterService;
import com.meirengu.webview.service.KwDfrzPushService;
import com.meirengu.webview.service.UserInfoService;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
 * KwDfrzFilter服务实现层
 *
 * @author Mao
 * @create Wed May 09 11:06:15 CST 2018
 */
@Service
public class KwDfrzFilterServiceImpl extends BaseServiceImpl<KwDfrzFilter> implements KwDfrzFilterService {


    @Autowired
    private RedisClient redisClient;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private KwInterfaceConfigDao kwInterfaceConfigDao;

    @Autowired
    private KwDfrzPushService kwDfrzPushService;


    Logger logger = LoggerFactory.getLogger(KwDfrzFilterServiceImpl.class);


    /**
     * 发送东方融资网接口
     * 过滤条件
     * 1.地址
     * 2.金额
     *
     * @param userInfo
     * @param user
     */
    public boolean sendEastFinance(UserInfo userInfo, User user) throws Exception {

        boolean sendFlag = false;
        try {
            String dfrzIol = redisClient.get("iol-dfrz");
            if ("N".equals(dfrzIol)) {
                Date brithdayDate = userInfo.getBirthday();
                String id = user.getId();
                String name = user.getName();
                String mobile = user.getMobile();
                Integer sex = user.getSex();

                String city = userInfo.getScity();
                Integer hasCar = userInfo.getCar();
                Integer housingType = userInfo.getHouse();
                BigDecimal expectAmount = userInfo.getExpectAmount();
                Integer socialSecurity = userInfo.getSocialSecurity();
                Integer paytype = userInfo.getSalaryMethod();
                Integer creditSituation = userInfo.getCredit();
                Integer profession = userInfo.getOccupation();
                Integer income = userInfo.getSalary();
                Integer worklong = userInfo.getWorkDuration();
                Integer housingFund = userInfo.getFund();
                int age = 25;
                age = DateUtils.getAge(brithdayDate);

                KwDfrzFilter kwDfrzFilter = new KwDfrzFilter();
                kwDfrzFilter.setUserId(id);
                kwDfrzFilter.setMobile(mobile);
                kwDfrzFilter.setChannelCode("dfrz");
                kwDfrzFilter.setChannelName("东方融资网");

                KwInterfaceConfig kwInterfaceConfig = kwInterfaceConfigDao.findByCode("dfrz");

                boolean dataFlag = true;
                if (kwInterfaceConfig != null) {
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitArea())) {
                        city = city.replace("市", "");
                        String cityRange = kwInterfaceConfig.getAreaValue();
                        if (!cityRange.contains(city)) {
                            dataFlag = false;
                            kwDfrzFilter.setSuited("N");
                            kwDfrzFilter.setCode(UserChannelEnum.FAIL_AREA.getValue());
                            kwDfrzFilter.setRefuseMsg("用户所在城市不满足：" + city);
                        }
                    }
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitAge())) {
                        if (age < kwInterfaceConfig.getMinAge().intValue() || age > kwInterfaceConfig.getMaxAge().intValue()) {
                            dataFlag = false;
                            kwDfrzFilter.setSuited("N");
                            kwDfrzFilter.setCode(UserChannelEnum.FAIL_AGE.getValue());
                            kwDfrzFilter.setRefuseMsg("用户年龄不符合：" + age);
                        }
                    }

                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitAmount())) {
                        if (expectAmount.intValue() < kwInterfaceConfig.getMinAmount() || expectAmount.intValue() > kwInterfaceConfig.getMaxAmount()) {
                            dataFlag = false;
                            kwDfrzFilter.setSuited("N");
                            kwDfrzFilter.setCode(UserChannelEnum.FAIL_LOW_AMOUNT.getValue());
                            kwDfrzFilter.setRefuseMsg("申请贷款额度小于" + kwInterfaceConfig.getMinAmount() + "w：" + expectAmount);
                        }
                    }
                    if (dataFlag) {
                        int aSex = sex.intValue() + 1;
                        int loanAmount = (expectAmount.divide(new BigDecimal(10000))).intValue();
                        int havenHouseLoan = 1;
                        if (housingType.intValue() == 1 || housingType.intValue() == 3) {
                            havenHouseLoan = 0;
                        }
                        int haveCarLoan = 1;
                        if (hasCar.intValue() == 1 || hasCar.intValue() == 3) {
                            haveCarLoan = 0;
                        }
                        //默认：有社保有公积金
                        int socialSecurityFund = 2;
                        // 无社保无公积金
                        if (socialSecurity.intValue() == 0 && housingFund.intValue() == 0) {
                            socialSecurityFund = 1;
                            //有社保无公积金
                        } else if (socialSecurity != 0 && housingFund.intValue() == 0) {
                            socialSecurityFund = 4;
                            //无社保有公积金
                        } else if (socialSecurity == 0 && housingFund.intValue() != 0) {
                            socialSecurityFund = 8;
                        }
                        int haveCreditCard = creditSituation.intValue() - 1;
                        //默认：企业主
                        int identity = 1;
                        // 上班族
                        if (profession == 0 || profession == 2) {
                            identity = 4;
                        }
                        int incomeDistributionType = paytype;
                        //默认：12-24个月
                        int workingAge = 8;
                        //6个月以下
                        if (worklong.intValue() == 6) {
                            workingAge = 2;
                            //12个月以下
                        } else if (worklong.intValue() == 12) {
                            workingAge = 4;
                        }
                        //默认：1w
                        int averageMonthlyIncome = 10000;
                        if (income.intValue() == 1) {
                            averageMonthlyIncome = 4000;
                        } else if (income.intValue() == 2) {
                            averageMonthlyIncome = 4500;
                        } else if (income.intValue() == 3 || income.intValue() == 4) {
                            averageMonthlyIncome = 7500;
                        }
                        String workingCity = city;
                        //信用卡额度 int N 无信用卡:1, 1-500 元 :2, 501-1000 元:4 ,1001-5000 元:8, 5001-8000 元:16 ,8001-10000 元:32 ,1000150000 元:64 ,50001-100000 元:128 ,100001 元及以上 :256
                        int creditCardAmount = 64;

                        int haveHouse = 1;
                        if (housingType.intValue() == 1) {
                            haveHouse = 2;
                        }
                        int haveCar = 1;
                        if (hasCar.intValue() == 1) {
                            haveCar = 2;
                        }
                        Integer code = kwDfrzPushService.registered(city, mobile, name, aSex, loanAmount,
                                age, havenHouseLoan, haveCarLoan, socialSecurityFund,
                                haveCreditCard, identity, incomeDistributionType,
                                workingAge, averageMonthlyIncome, workingCity,
                                creditCardAmount, haveHouse, haveCar);
                        kwDfrzFilter.setSuited("Y");
                        kwDfrzFilter.setCode(UserChannelEnum.PASS.getValue());
                        /*推送接口后修改限制数量*/
                        userInfoService.updateLimitNum(code, "dfrz", user);
                        if (code.intValue() == Constants.BUSINESS_STATUS_SUCCESS) {
                            sendFlag = true;
                        }
                    }
                }

                insert(kwDfrzFilter);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        }
        return sendFlag;
    }
}
